package com.pjhouse.pipeline.security;


import com.alibaba.citrus.util.StringUtil;
import org.springframework.beans.factory.InitializingBean;

import java.util.*;

/**
 * @author jingsheng
 * @description 判断哪些target是需要保护的
 *
 */
public class UrlProtectMappingServiceImpl implements UrlProtectMappingService, InitializingBean {

	private static final String SEP_SLASH = "/";
	private static final String SEP_SEMICOLON = ":";
	/**
	 * 受保护的 URL 集合，Set<String>
	 */
	private List<String> unprotectedUrls;
	
	public List<String> getUnprotectedUrls() {
		return unprotectedUrls;
	}


	public void setUnprotectedUrls(List<String> unprotectedUrls) {
		this.unprotectedUrls = unprotectedUrls;
	}


	private List<String> unprotectedPaths;
	private Map<String, Set<String>> pathMap = new HashMap<String, Set<String>>();

	public List<String> getUnprotectedPaths() {
		return unprotectedPaths;
	}


	public void setUnprotectedPaths(List<String> unprotectedPaths) {
		this.unprotectedPaths = unprotectedPaths;
	}


	public boolean isURLUnProtected(String target) {
			boolean flag=false;
			if(unprotectedUrls.contains(target)){
				return true;
			}
			String t = target.substring(0, target.lastIndexOf(SEP_SLASH));
			String[] pathArr = StringUtil.split(t, SEP_SLASH);
			String p = "";
			for (int i = 0; i < pathArr.length; i++) {
				p = p + SEP_SLASH + pathArr[i];
				final Set<String> unprotectedURL = pathMap.get(p);
				if (unprotectedURL != null && !unprotectedURL.contains(target)) {
					flag = true;
					break;
				}
			}
		return flag;
	}
	

	@Override
	public void afterPropertiesSet() throws Exception {
		if (unprotectedPaths != null) {
			for (String path : unprotectedPaths) {
				int i = -1;
				String p = path;
				String url = null;
				if ((i = path.indexOf(SEP_SEMICOLON)) > 0 && i < path.length()) {
					p = path.substring(0, i);
					url = path.substring(i + SEP_SEMICOLON.length());
				}
				if (p.endsWith(SEP_SLASH)) {
					p = p.substring(0, p.length() - SEP_SLASH.length());
				}

				Set<String> protectedURLSet = pathMap.get(p);
				if (protectedURLSet == null) {
					protectedURLSet = new HashSet<String>();
					pathMap.put(p, protectedURLSet);
				}
				if (!StringUtil.isBlank(url)) {
					protectedURLSet.add(url);
				}
			}
		}
	}
}
